'''xiami.py

Some utilities of Xiami Music
'''
import logging

import requests
from bs4 import BeautifulSoup as Soup

# Another widly used user-agent
UA = '''
Mozilla/5.0 (Windows NT 10.0; WOW64) \
AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/60.0.3112.113 Safari/537.36\
'''

# Create a module-level session
SESSION = requests.Session()
# Update user-agent of session
SESSION.headers.update({'User-Agent': UA})
# Initiate some cookies might be needed
SESSION.get(r'http://www.xiami.com')
# Shortcut of HTTP GET
GET = SESSION.get


def myfavo(userid):
    '''Get Xiami 'Favorite' playlist.

    Fetching information of songs from the first page,
    until there don't have any entry of songs.

    Args:
        userid (has __repr__): User ID

    Returns:
        generator of:
            str: Name of the song
            str: Hyperlink of detailed information of
                 the song
            list of:
                str: Name of the author
                str: Hyperlink of detailed information
                     of the author
    '''
    logger = logging.getLogger('utils.xiami.myfavo')
    pagenum = 1
    while True:
        url = f'http://www.xiami.com/space/lib-song/u/{userid}/page/{pagenum}'
        logger.info('Fetching page %s for userid %s.', pagenum, userid)
        page = GET(url)
        soup = Soup(page.text)
        songs = soup.find_all('td', {'class': 'song_name'})
        if not songs:
            logger.info('Song entry not found at page %s, exited.', pagenum)
            break
        else:
            logger.info('Page %s fetched. Analyzing.', pagenum)
            pagenum += 1
        for song in songs:
            song_title = song.a
            song_artists = song.find_all('a', {'class': 'artist_name'})
            yield ((song_title['title'], song_title['href']),
                   [(elemt['title'], elemt['href']) for elemt in song_artists])


def search_song(key):
    '''Search songs via Xiami Searcher

    Performing a song search via http://www.xiami.com/search/song

    Args:
        key (str or bytes): Searching keyword

    Returns:
        generator of:
            str: Name of the song
            str: Hyperlink of detailed information of
                 the song
            list of:
                str: Name of the author
                str: Hyperlink of detailed information
                     of the author
            str: Name of the album
            str: Hyperlink of detailed information of
                 the album
    '''
    logger = logging.getLogger('utils.xiami.search_song')
    payload = {'key': key, 'category': -1}
    pagenum = 1
    while True:
        url = f'http://www.xiami.com/search/song/page/{pagenum}'
        logger.info('Fetching page %s for keywords %s.', pagenum, key)
        page = GET(url, params=payload)
        soup = Soup(page.text)
        try:
            songfield = soup.find('table', {'class': 'track_list'}).tbody
            songs = songfield.find_all('tr')
        except AttributeError as attrerr:
            logger.debug(attrerr)
            songs = None
        if not songs:
            logger.info('Song entry not found at page %s, exited.', pagenum)
            break
        else:
            logger.info('Page %s fetched. Analyzing.', pagenum)
            pagenum += 1
        for song in songs:
            song_title = song.find('td', {
                'class': 'song_name'
            }).find('a', {'target': '_blank'})

            song_artists = song.find('td', {
                'class': 'song_artist'
            }).find_all('a', {'target': '_blank'})

            song_album = song.find('td', {
                'class': 'song_album'
            }).find('a', {'target': '_blank'})

            yield ((song_title['title'], song_title['href']),
                   [(elemt['title'], elemt['href']) for elemt in song_artists],
                   (song_album['title'], song_album['href']))


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    #for item in myfavo(267883203):
    #    print(item)

    #for item in search_song('吹雪'):
    #    print(item)

    print(__doc__)
